import axios from 'axios';
import url from 'postcss-url';


//  创建axios实例--获取后台数据
const requests = axios.create({
    baseURL: 'https://www.runoob.com',
    timeout: 6000
});

//  错误处理 函数
const err = (error) => {
  if (error.response) {
      const data = error.response.data;
    if (error.response.status === 403) {
      this.$message({ message: data.message, type: 'warning' });
    }
    if (error.response.status === 401) {
        this.$message({ message: '你没有权限', type: 'warning' });
        // todo 加token验证
    }
  }
  return Promise.reject(error);
};

//  请求拦截器
requests.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  console.log(token);
  if (token) {
      config.headers['token'] = token;  // 让每个请求都携带自定义的token， todo   后边根据实际情况再修改
  }
  return config;
}, err);

//  接受拦截器
requests.interceptors.response.use((response) => {
    console.log(response);
    return response.data;
  const res = response.data;
  if (res.code !== 0 && res.code !== 200) {
      this.$message({message: data.message, type: 'warning'})
      if (res.code === 401 || res.code === 403 || res.code === 999) {
          this.$message({message: '请登录', type: 'warning'})
      }
  } else {
      return res;
  }
}, err);

// 重新封装后端数据get方法
requests.httpGet = (url, params = {}) => {
  return new Promise((resolve,reject) => {
    requests.get(url,{
        params:params
      })
      .then(response => {
        resolve(response);
      })
      .catch(err => {
        reject(err)
      });
  });
}
//  重新封装后端数据post方法
requests.httpPost = ({
  url,
  data = {},
  params = {}
}) => {
  return new Promise((resolve, reject) => {
    requests({
      url, method: 'POST', transformRequest: [(data) => {
        let ret = '';
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret;
      }],
      // 发送的数据
      data,
      //  url参数
      params
    }).then(res => {
      console.log(res);
      resolve(res);
    });
  });
}

//  创建axios实例--获取前端静态数据
const getLocalData = axios.create({
  baseURL: 'localhost:8080/src/assets/data',
  timeout: 6000
});
getLocalData.localGet = (url, params = {}) => {
  return new Promise((resolve,reject) => {
    requests.get(url,{
        params:params
      })
      .then(response => {
        resolve(response);
      })
      .catch(err => {
        reject(err)
      });
  });
}
export default {
    requests
}
